package com.bwie.policy;

import cn.hutool.core.util.RandomUtil;
import com.bwie.mapper.TbPolicyMapper;
import com.bwie.pojo.TbPolicy;
import com.bwie.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @projectName: server-2211a-red
 * @package: com.bwie.policy
 * @className: SingleRedPolicy
 * @author: 杨珂
 * @description: TODO
 * @date: 2025/6/9 16:47
 * @version: 1.0
 */
@Component
public class SingleRedPolicy implements IRedPolicy {

    TbPolicy policy = null;
    Integer userId = null;

    @Autowired
    StringRedisTemplate redisTemplate;


    public void setPolicy(TbPolicy tbPolicy, Integer userId) {
        this.policy = tbPolicy;
        this.userId = userId;
    }


    @Override
    public Result exe() {
        System.out.println("完成默认单红包策略");
        String key = "red-" + userId + policy.getPolicyId();

        //如果key不存在从来没有执行抢过红包
        Boolean hasKey = redisTemplate.hasKey(key);
        if (!hasKey) {

            redisTemplate.opsForValue().set(key, "0");

            //抢红包
            double amount = RandomUtil.randomDouble(0.01, policy.getPacketAmount());

            //记录红包明细


        } else {

            Long decrement = redisTemplate.opsForValue().decrement(key);
            if (decrement < 0) {
                return Result.error().setMsg("已经抢过红包");
            }
        }


        return Result.ok();
    }
}
